<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Library\clt\Leftnav;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
/**
 * 控制器创建: php artisan make:controller Admin/AuthController
 */
class AuthController extends CommonController
{
    /**
     * 管理员列表
     * 占位符：select * from laravel_admins where id=:id and is_open=:is_open,array('id'=>1,'is_open'=>1);
     */
    public function adminlist(Request $request)
    {
        //dd(1);
        /* DB::connection()->enableQueryLog();
         $count = DB::select("explain select count(1) as aggregate from `laravel_admins`", [1]);
         dump($count[0]->rows);
         dump(DB::getQueryLog());*/

        /*       dump($list);*/
        if($request->isMethod('post')){
            $map = [];
            $count = DB::table("admins")->count('id');
            $key = $request->key;
            $page = $request->page?$request->page:1;
            $limit = $request->limit?$request->limit:10;
            $is_open = $request->is_open;
            if(is_numeric($is_open)){
                $map['a.is_open'] = $is_open;
            }
            if(!empty($key)){
                $map[] = ['a.username', 'like', '%'.$key.'%'];
            }
            $offset = ($page - 1) * $limit;
            $list = DB::table("admins as a")
                ->select('a.*','b.title')
                ->leftJoin('auth_group as b', 'a.group_id', '=', 'b.group_id')
                ->where($map)
                ->offset($offset)
                ->limit($limit)
                ->get()
                ->toArray();
            return response()->json(['code'=>0,'msg'=>'获取成功!'.$page,'data'=>$list,'count'=>$count]);
        }else{
            return view('admin/auth/adminlist');
        }
    }

    /**
     * 添加管理员
     */
    public function adminadd(Request $request)
    {
        if($request->isMethod('post')){
            $data = $request->only(['username','group_id','password','avatar']);
            $data['password'] = bcrypt($data['password']);
            //表单验证
            $validator = Validator::make(($data),[
                'username' => ['unique:admins'],
            ],[
                'username.unique'=>'用户名已经存在',
            ]);
            if ($validator->fails()) {
                return response()->json([
                    'code' => 0,
                    'msg'  => $validator->errors()->first(),
                ], 200);
            }
            $data['ip'] = $request->ip();
            $data['addtime'] = time();
            $insert =  DB::table('admins')->insert($data);
            if($insert){
                return  response()->json(['code'=>1,'msg'=>'添加成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'添加失败']);
            }
        }else{
            //用户组列表信息
            $group = DB::table('auth_group')->get()->toArray();
            return view('admin/auth/adminadd')->with('group',$group);
        }
    }

    /**
     * 编辑管理员
     */
    public function adminedit(Request $request)
    { 
        if($request->isMethod('post')){
            $id = $request->id;
            $sql = DB::table('admins')->where('id',$id)->first();
            $sql = json_decode(json_encode($sql),true);
            $data = $request->only(['username','group_id','avatar']);
            //判断图片是够存在，存在进行删除
            if($sql['avatar'] != $data['avatar'] && $sql['avatar']!= ""){
                $avatar=str_replace('/uploads/','',$sql['avatar']);
                //删除旧图片
                Storage::delete($avatar);
            }
            //表单验证
            $validator = Validator::make($data,[
                'username' => [Rule::unique('admins')->ignore($id)],
            ],[
                'username.unique'=>'用户名已经存在',
            ]);
            if ($validator->fails()) {
                return response()->json([
                    'code' => 0,
                    'msg'  => $validator->errors()->first(),
                ], 200);
            }
            $update = DB::table('admins')->where('id',$id)->update($data);
            if($update){
                return  response()->json(['code'=>1,'msg'=>'编辑成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'编辑失败']);
            }
        }else{
            //用户组列表信息
            $group = DB::table('auth_group')->get()->toArray();
            $id = $request->id;
            $info = DB::table('admins')->where('id',$id)->first();
            $info = json_decode(json_encode($info),true);
            return view('admin/auth/adminedit')->with('group',$group)->with('info',$info);
        }
    }

    /**
     * 管理员状态
     */
    public function adminstatus(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            $data = $request->only(['is_open']);
            $update = DB::table('admins')->where(['id'=>$id])->update($data);
            if($update){
                return  response()->json(['code'=>1,'msg'=>'编辑成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'编辑失败']);
            }
        }

    }

    /**
     * 编辑管理员密码
     */
    public function editpass(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            $password = $request->password;
            $password = bcrypt($password);
            $update = DB::table('admins')->where(['id'=>$id])->update(['password'=>$password]);
            if($update){
                return  response()->json(['code'=>1,'msg'=>'编辑成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'编辑失败']);
            }
        }else{
            return view('admin/auth/editpass')->with('id',$request->id);
        }
    }


    /**
     * 删除管理员
     */
    public function admindel(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            if(!is_array($id)){
                $id = explode(',',$id);
            }
            $idinfo = $request->user()->id;
            if($idinfo != 1){
                return  response()->json(['code'=>1,'msg'=>'您没有删除管理员的权限']);
            }
            $info =DB::table('admins')->where('id',$id)->first();
            $info = json_decode(json_encode($info),true);
            if($info['avatar']){
                $avatar=str_replace('/uploads/','',$info['avatar']);
                //删除旧图片
                Storage::delete($avatar);
            }
            $delete = DB::table('admins')->whereIn('id',$id)->delete();
            if($delete){
                return  response()->json(['code'=>1,'msg'=>'删除成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'删除失败']);
            }
        }
    }

    /**
     * 上传图片
     */
    public function upimagesinfo(Request $request)
    {
        if($request->isMethod('post')){
            if($request->file('file')){
                $id = $request->post('adminid');
                $info = DB::table('admins')->where('id',$id)->first();
                $info = json_decode(json_encode($info),true);
                if($info['avatar']){
                    $avatar=str_replace('/uploads/','',$info['avatar']);
                    //删除旧图片
                    Storage::delete($avatar);
                }
                $files = $request->post('files');
                $url = $request->file('file')->store($files);
                $data['avatar'] = '/uploads/'.$url;
                $update = DB::table('admins')->where('id',$id)->update($data);
                if($update){
                    return  response()->json(['code'=>1,'msg'=>'上传成功']);
                }else{
                    return  response()->json(['code'=>0,'msg'=>'上传失败']);
                }
            }else{
                // 上传失败获取错误信息
                return response()->json(['code' => 0, 'msg' => '上传文件不能为空!']);
            }
        }
    }

    /**
     * 用户组列表
     */
    public function authgroup(Request $request)
    {
        if($request->isMethod('post')){
            $map = [];
            $count = DB::table("auth_group")->count('group_id');
            /*            $map['group_id'] =  [1, 2, 3];*/
            $key = $request->key;
            $page = $request->page?$request->page:1;
            $limit = $request->limit?$request->limit:10;
            $map[] = ['title', 'like', '%'.$key.'%'];
            $offset = ($page - 1) * $limit;
            $list = DB::table("auth_group")->where($map)->offset($offset)->limit($limit)->get()->toArray();
            return response()->json(['code'=>0,'msg'=>'获取成功!','data'=>$list,'count'=>$count]);
        }else{
            return view('admin/auth/authgroup');
        }
    }

    /**
     * 添加用户组
     */
    public function groupadd(Request $request)
    {
        if($request->isMethod('post')){
            $data['title'] = $request->post('title');
            //表单验证
            $validator = Validator::make(($data),[
                'title' => ['unique:auth_group'],
            ],[
                'title.unique'=>'用户组名已经存在',
            ]);
            if ($validator->fails()) {
                return response()->json([
                    'code' => 0,
                    'msg'  => $validator->errors()->first(),
                ], 200);
            }
            $data['addtime'] = time();
            $insert =  DB::table('auth_group')->insert($data);
            if($insert){
                return  response()->json(['code'=>1,'msg'=>'添加成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'添加失败']);
            }
        }else{
            return view('admin/auth/groupadd');
        }
    }

    /**
     * 编辑用户组
     */
    public function groupedit(Request $request)
    {
        if($request->isMethod('post')){
            $group_id = $request->group_id;
            $title = $request->title;
            //表单验证
            $validator = Validator::make(($request->post()),[
                'title' => ['unique:auth_group'],
            ],[
                'title.unique'=>'用户组名已经存在',
            ]);
            if ($validator->fails()) {
                return response()->json([
                    'code' => 0,
                    'msg'  => $validator->errors()->first(),
                ], 200);
            }
            $update = DB::table('auth_group')->where(['group_id'=>$group_id])->update(['title'=>$title]);
            if($update){
                return  response()->json(['code'=>1,'msg'=>'编辑成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'编辑失败']);
            }
        }else{
            $id = $request->id;
            $info = DB::table('auth_group')->where('group_id',$id)->select('group_id','title')->first();
            return view('admin/auth/groupedit')->with('info',$info);
        }
    }

    /**
     * 分配权限
     */
    public function groupaccess(Request $request)
    {
        if($request->isMethod('post')){
            $rules = $request->rules;
            $id = $request->group_id;
            if(empty($rules)){
                return ['msg'=>'请选择权限进行配置!','code'=>0];
            }
            $update = DB::table('auth_group')->where('group_id',$id)->update(['rules'=>$rules]);
            if($update){
                return ['msg'=>'设置成功!','code'=>1];
            }else{
                return ['msg'=>'设置失败!','code'=>0];
            }
        }else{
            $id = $request->id;
            $nav = new Leftnav();
            $admin_rule = DB::table('auth_rule')->select('id','pid','title')->orderByRaw('sort asc,title desc')->get();
            $admin_rule = json_decode($admin_rule, true);
            $rules = DB::table('auth_group')->where('group_id',$id)->value('rules');
            $arr = $nav->auth($admin_rule,$pid=0,$rules);
            $arr[] = array(
                "id"=>0,
                "pid"=>0,
                "title"=>"全部",
                "open"=>true
            );
            return view('admin/auth/groupaccess')->with('data',json_encode($arr,true))->with('idinfo',$id);
        }
    }

    /**
     * 删除用户组
     */
    public function groupdel(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            if(!is_array($id)){
                $id = explode(',',$id);
            }
            $delete = DB::table('auth_group')->whereIn('group_id',$id)->delete();
            if($delete){
                return  response()->json(['code'=>1,'msg'=>'删除成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'删除失败']);
            }
        }
    }

    /**
     * 权限列表
     */
    public function authrule(Request $request)
    {
 
        if($request->isMethod('post')){
            $map = [];
            $key = $request->key;
            $types = $request->types;
            $pageSize = $request->limit;
            /**
             * 关键字搜索
             */
            if(!empty($key) && !empty($types)){
                $map[] = [$types, 'like', '%'.$key.'%'];
            }
            $nav = new Leftnav();
            $authRule = DB::table('auth_rule')->where($map)->orderByRaw('sort asc,title desc')->paginate($pageSize)->toArray();
            $authRule = json_decode(json_encode($authRule),true);
            $authRules = DB::table('auth_rule')->where($map)->orderByRaw('sort asc,title desc')->where('pid',0)->paginate($pageSize)->toArray();
            $arr = $nav->menu($authRule['data']);
            return response()->json(['code'=>0,'msg'=>'获取成功!','data'=>$arr,'count'=>$authRules['total']]);
        }else{
            return view('admin/auth/authrule');
        }
    }

    /**
     * 添加权限
     */
    public function ruleadd(Request $request)
    {
        if($request->isMethod('post')){
            $data = $request->only(['pid', 'title', 'href','icon','menustatus','sort']);
            if($data['pid'] == 0){
                $data['levels'] = 1;
            }else{
                $levels =  DB::table('auth_rule')->select('levels')->where('id',$data['pid'])->first();
                $data['levels'] = ($levels->levels)+1;
            }
            $data['addtime'] = time();
            $insert =  DB::table('auth_rule')->insert($data);
            if($insert){
                return  response()->json(['code'=>1,'msg'=>'添加成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'添加失败']);
            }
        }else{
            $nav = new Leftnav();
            $authRule =  DB::table('auth_rule')->orderByRaw('sort asc,title desc')->get();
            $authRule = json_decode($authRule, true);
            $arr = $nav->menu($authRule);
            $pid = $request->pid;
            return view('admin/auth/ruleadd')->with('admin_rule',$arr)->with('pid',$pid);
        }
    }

    /**
     * 编辑权限
     */
    public function ruleedit(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            $data = $request->only(['pid', 'title', 'href','icon','sort']);
            if($data['pid'] == 0){
                $data['levels'] = 1;
            }else{
                $levels =  DB::table('auth_rule')->select('levels')->where('id',$data['pid'])->first();
                $data['levels'] = ($levels->levels)+1;
            }
            $update = DB::table('auth_rule')->where(['id'=>$id])->update($data);
            if($update){
                return  response()->json(['code'=>1,'msg'=>'编辑成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'编辑失败']);
            }
        }else{
            $id = $request->id;
            $nav = new Leftnav();
            $authRule =  DB::table('auth_rule')->orderByRaw('sort asc,title desc')->get();
            $authRule = json_decode($authRule, true);
            $arr = $nav->menu($authRule);
            $info = DB::table('auth_rule')->where('id',$id)->first();
            $info = json_decode(json_encode($info),true);
            return view('admin/auth/ruleedit')->with('admin_rule',$arr)->with('info',$info);
        }
    }

    /**
     * 权限管理设置菜单状态
     */
    public function menustatus(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            $data = $request->only(['menustatus']);
            $update = DB::table('auth_rule')->where(['id'=>$id])->update($data);
            if($update){
                return  response()->json(['code'=>1,'msg'=>'编辑成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'编辑失败']);
            }
        }

    }

    /**
     * 删除用户组
     */
    public function ruledel(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            if(!is_array($id)){
                $id = explode(',',$id);
            }
            $pid =DB::table('auth_rule')->where('pid',$id)->first();
            if($pid){
                return response()->json(['code'=>0,'msg'=>'不能进行删除,下级有分类']);
            }
            $delete = DB::table('auth_rule')->whereIn('id',$id)->delete();
            if($delete){
                return  response()->json(['code'=>1,'msg'=>'删除成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'删除失败']);
            }
        }
    }

    /**
     * 权限管理排序
     */
    public function rulesort(Request $request)
    {
        if($request->isMethod('post')){
            $id = $request->id;
            $data = $request->only(['sort']);
            $update = DB::table('auth_rule')->where(['id'=>$id])->update($data);
            if($update){
                return  response()->json(['code'=>1,'msg'=>'编辑成功']);
            }else{
                return  response()->json(['code'=>0,'msg'=>'编辑失败']);
            }
        }

    }

}
